<template>
	<view class="wrap">
		<van-search v-model="inp" shape="round" placeholder="搜索商品" />
		<view class="cont">
			<view v-for="v in list" class="item">
				<img :src="v.productImg" class="bigimg" @click="goodsinfo(v.productId)" />
				<view class="name">{{v.productName}}</view>
				<view class="price">
					<view>￥{{v.productPrice}}</view>
					<van-icon name="cart-circle" color="#f6b37c" size="40rpx" @click="addcart(v.productId)" />
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import $http from '../../request/index.js'
	import {
		showSuccessToast,
		showFailToast
	} from 'vant'
	let list = ref([])
	let classify = ref('')
	// 每次进来加载商品的所有信息
	onShow(() => {
		$http.get('/shopping/all').then(res => { //得到所有商品
			console.log(res)
			if (classify.value.length) {
				console.log('111')
				list.value = res.data.filter((i, k) => i.productCategory == classify.value)
				console.log(list.value)
			}
		})
	})
	let inp = ref('')

	function addcart(id) { //点击添加购物车
		// 发送请求，带上商品id,加购数量，一次加一个
		$http.get('/shopping/addcart', {
			productId: id,
			productNum: 1
		}).then(res => {
			let {
				code,
				msg
			} = res
			if (!code) {
				showSuccessToast(msg)
			} else {
				showFailToast(msg)
			}
		})
	}

	function goodsinfo(id) { //跳转到商品详情
		uni.navigateTo({
			url: '/pages/goodsinfo/goodsinfo?id=' + id
		})
	}
	onLoad((name) => { //接收从上个页面传过来的分类名字
		classify.value = name.classify
		////动态改navbar名字
		uni.setNavigationBarTitle({
			title: name.classify
		})
	})
</script>

<style scoped>
	.wrap {
		width: 100vw;
		height: calc(100vh - 44px);
		overflow-y: scroll;
		padding-bottom: 50px;
		background-color: #f7f7f7;
	}

	.cont {
		display: flex;
		flex-wrap: wrap;
		width: 100vw;
		justify-content: space-evenly;
	}

	.item {
		width: 340rpx;
		background-color: #ffffff;
		padding: 20rpx;
		box-sizing: border-box;
		text-align: center;
		border-radius: 26rpx;
		margin: 10rpx 0;
	}

	.name {
		font-size: 26rpx;
		margin: 10rpx 0;
		color: gray;
	}

	.price {
		width: 100%;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 26rpx;
		color: #Fe9b23;
	}

	.bigimg {
		width: 300rpx;
		height: 300rpx;
	}
</style>